package com.lxd.api.filter.Impl;

import com.lxd.api.feign.cacheClient;
import com.lxd.api.filter.CheckFilter;
import com.lxd.common.constants.ApiConstant;
import com.lxd.common.constants.CacheConstant;
import com.lxd.common.enums.ExceptionEnums;
import com.lxd.common.exception.ApiException;
import com.lxd.common.model.StandardSubmit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Set;

@Service(value = "sign")
@Slf4j
public class SignCheckFilter implements CheckFilter {
    @Autowired
    private cacheClient client;




    @Override
    public void check(StandardSubmit submit) {
        //从text提取出 要被校验的sign
        String text = submit.getText();
        //校验text中是否存在 【】
        if (!text.contains(ApiConstant.SING_PREFIX) || !text.contains(ApiConstant.SING_SUFFIX)){
            log.info("【接口模块-校验sign】 sign不包含前后缀，校验失败");
            throw new ApiException(ExceptionEnums.ERROR_SIGN);
        }

        //】的索引位置
        log.info("【接口模块-校验sign】 正在截取text中的sign");
        int suffixIndex = text.indexOf(ApiConstant.SING_SUFFIX);
        String submitSign = text.substring(ApiConstant.SIGN_START_INDEX, suffixIndex);//截取出要被校验的sign

        //通过client id 从缓存中查到对应的签名
        log.info("【接口模块-校验sign】 正在查询客户的sign");
        Long clientId = submit.getClientId();
        Set<Map> signs = client.smembers(CacheConstant.CLIENT_SIGN + clientId);

        log.info("【接口模块-校验签名】sign 开始进行比对…………");
        for (Map sign : signs) {
            if (submitSign.equals(sign.get(ApiConstant.SIGN_INFO))){
                submit.setSignId( (Integer) sign.get(ApiConstant.SIGN_ID));// 封装sign ID
                submit.setSign((String) sign.get(ApiConstant.SIGN_INFO));//封装sign
                //校验成功
                log.info("【接口模块-校验sign】 校验通过！！");
                return;
            }
        }
        log.info("【接口模块-校验sign】 sign校验未通过!!");
        throw new ApiException(ExceptionEnums.ERROR_SIGN);
    }
}
